import { defineStore } from 'pinia';
import type {
  ComponentInstance,
  LowcodeState,
  LowcodeGetters,
  LowcodeActions,
} from '@/types/lowcode';

export const useLowcodeStore = defineStore<'lowcode', LowcodeState, LowcodeGetters, LowcodeActions>(
  'lowcode',
  {
    state: () => ({
      canvasComponents: [],
      selectedComponentId: null,
    }),
    actions: {
      addComponentInstance(component: ComponentInstance) {
        this.canvasComponents.unshift(component);
        this.selectedComponentId = component.id;
      },
      setSelectedComponentId(id: string | number | null) {
        this.selectedComponentId = id;
      },
      updateComponentInstance(updatedComponent: ComponentInstance) {
        const index = this.canvasComponents.findIndex((c) => c.id === updatedComponent.id);
        if (index !== -1) {
          this.canvasComponents[index] = { ...updatedComponent };
        }
      },
      removeComponentInstance(id: string) {
        this.canvasComponents = this.canvasComponents.filter((c) => c.id !== id);
        if (this.selectedComponentId === id) {
          this.selectedComponentId = null;
        }
      },
    },
    getters: {
      getSelectedComponent: (state): ComponentInstance | undefined => {
        return state.selectedComponentId
          ? state.canvasComponents.find((c) => c.id === state.selectedComponentId)
          : undefined;
      },
    },
  },
);
